<template>
  <div class="app-container">
    <!-- 查询表单 - 布局优化和tooltip -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" :label-width="queryFormLabelWidth">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input
                v-model="queryParams.deviceName"
                placeholder="请输入设备名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分类ID" prop="categoryId">
            <el-input
                v-model="queryParams.categoryId"
                placeholder="请输入分类ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备型号" prop="model">
            <el-input
                v-model="queryParams.model"
                placeholder="请输入设备型号"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备规格" prop="specification">
            <el-input
                v-model="queryParams.specification"
                placeholder="请输入设备规格"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="制造商" prop="manufacturer">
            <el-input
                v-model="queryParams.manufacturer"
                placeholder="请输入制造商"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商" prop="supplier">
            <el-input
                v-model="queryParams.supplier"
                placeholder="请输入供应商"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购时间" prop="purchaseDate">
            <el-date-picker clearable
                            v-model="queryParams.purchaseDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择采购时间"
                            style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="status">
            <template #label>
              <!-- 修正设备状态label，添加tooltip -->
              <el-tooltip content="0-停用,1-启用,2-维修中,3-报废" placement="top">
                <span>设备状态</span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable style="width: 100%;">
              <el-option
                  v-for="dict in device_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="安装位置" prop="location">
            <el-input
                v-model="queryParams.location"
                placeholder="请输入安装位置"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="18" style="text-align: right;">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 统计图表区域 START -->
    <el-card class="box-card mb8 chart-section">
      <template #header>
        <div class="card-header">
          <span>设备信息概览统计</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="12">
          <div id="deviceStatusChart" class="chart-container"></div>
        </el-col>
        <el-col :span="12">
          <div id="manufacturerChart" class="chart-container"></div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 统计图表区域 END -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['device:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['device:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        v-hasPermi="['device:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['device:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主表格 - 列宽优化和tooltip -->
    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备ID" align="center" prop="id" width="80" />
      <el-table-column label="设备名称" align="center" prop="deviceName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="分类ID" align="center" prop="categoryId" width="80" />
      <el-table-column label="设备型号" align="center" prop="model" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="设备规格" align="center" prop="specification" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="制造商" align="center" prop="manufacturer" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="供应商" align="center" prop="supplier" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="采购时间" align="center" prop="purchaseDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安装位置" align="center" prop="location" width="150" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="status" width="100">
        <template #header>
          <!-- 修正设备状态列头，添加tooltip -->
          <el-tooltip content="0-停用,1-启用,2-维修中,3-报废" placement="top">
            <span>设备状态</span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="device_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="设备描述" align="center" prop="description" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:info:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:info:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改设备基本信息对话框 - 尺寸、布局优化和tooltip -->
    <el-dialog :title="title" v-model="open" width="860px" append-to-body>
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类ID" prop="categoryId">
              <el-input v-model="form.categoryId" placeholder="请输入分类ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入设备型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备规格" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入设备规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入制造商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购时间" prop="purchaseDate">
              <el-date-picker clearable
                              v-model="form.purchaseDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择采购时间"
                              style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入安装位置" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="status">
              <template #label>
                <!-- 修正设备状态label，添加tooltip -->
                <el-tooltip content="0-停用,1-启用,2-维修中,3-报废" placement="top">
                  <span>设备状态</span>
                </el-tooltip>
              </template>
              <el-select v-model="form.status" placeholder="请选择设备状态" style="width: 100%;">
                <el-option
                    v-for="dict in device_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">故障报修信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddFaultReport">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteFaultReport">删除</el-button>
          </el-col>
        </el-row>
        <!-- 子表格 - 列宽优化和tooltip，并设置max-height -->
        <el-table :data="faultReportList" :row-class-name="rowFaultReportIndex" @selection-change="handleFaultReportSelectionChange" ref="DFaultReport" max-height="300px">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          <el-table-column label="故障标题" prop="faultTitle" width="150" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.faultTitle" placeholder="请输入故障标题" />
            </template>
          </el-table-column>
          <el-table-column prop="faultLevel" width="130">
            <template #header>
              <!-- 修正故障等级列头，添加tooltip -->
              <el-tooltip content="1-紧急,2-重要,3-一般" placement="top">
                <span>故障等级</span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-select v-model="scope.row.faultLevel" placeholder="请选择等级">
                <el-option
                    v-for="dict in fault_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="报修人" prop="reportBy" width="120" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.reportBy" placeholder="请输入报修人" />
            </template>
          </el-table-column>
          <el-table-column label="报修时间" prop="reportTime" width="160">
            <template #default="scope">
              <el-date-picker clearable
                              v-model="scope.row.reportTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="status" width="120">
            <template #header>
              <!-- 修正状态列头，添加tooltip -->
              <el-tooltip content="0-待处理,1-处理中,2-已解决,3-已关闭" placement="top">
                <span>状态</span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态">
                <el-option
                    v-for="dict in fault_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <!-- 假设增加一个故障描述字段，用于展示长文本 -->
          <el-table-column label="故障描述" prop="faultDesc" min-width="150" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.faultDesc" type="textarea" :rows="1" placeholder="请输入故障描述" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Info">
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/device/info"
import * as echarts from 'echarts'; // 引入 ECharts
import { onMounted, onBeforeUnmount, ref, reactive, toRefs, getCurrentInstance } from 'vue'; // 明确引入Vue Composition API函数

const { proxy } = getCurrentInstance()
// 注意：fault_level, fault_status 是故障报修模块的字典，这里主要用 device_status
const { device_status, fault_level, fault_status } = proxy.useDict('device_status', 'fault_level', 'fault_status')

const infoList = ref([]) // 修正：已统一为 infoList
const faultReportList = ref([]) // 子表数据
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedFaultReport = ref([]) // 子表选中项
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 为查询表单设置一个合理的label-width，可以根据实际情况调整
const queryFormLabelWidth = ref('80px'); // 保持为响应式变量

// ECharts 实例引用
let deviceStatusChartInstance = null;
let manufacturerChartInstance = null;

const data = reactive({
  form: {
    // 确保faultReportList在form中初始化，避免新增时报错
    faultReportList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: null,
    categoryId: null,
    model: null,
    specification: null,
    manufacturer: null,
    supplier: null,
    purchaseDate: null,
    location: null,
    status: null,
    description: null,
  },
  rules: {
    deviceName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "分类ID不能为空", trigger: "blur" }
    ],
    location: [
      { required: true, message: "安装位置不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "设备状态不能为空", trigger: "change" }
    ],
    // createTime 和 updateTime 通常由后端自动维护，无需前端校验
  }
})

const { queryParams, form, rules } = toRefs(data)

/**
 * 节流函数
 */
const throttle = (func, delay) => {
  let timeoutId;
  let lastArgs;
  let lastThis;

  return function(...args) {
    lastArgs = args;
    lastThis = this;

    if (!timeoutId) {
      timeoutId = setTimeout(() => {
        func.apply(lastThis, lastArgs);
        timeoutId = null;
        lastArgs = null;
        lastThis = null;
      }, delay);
    }
  };
};

/**
 * 根据数据聚合图表所需的数据
 * @param {Array} dataList - 设备列表数据
 */
function aggregateChartData(dataList) {
  if (!dataList || dataList.length === 0) {
    // 数据为空时，清空图表并显示无数据状态
    updateDeviceStatusChart([]);
    updateManufacturerChart([]);
    return;
  }

  const statusCounts = {};
  const manufacturerCounts = {};

  dataList.forEach(item => {
    // 聚合设备状态
    const statusDict = device_status.value.find(d => parseInt(d.value) === item.status);
    const statusLabel = statusDict ? statusDict.label : '未知状态';
    statusCounts[statusLabel] = (statusCounts[statusLabel] || 0) + 1;

    // 聚合制造商
    const manufacturer = item.manufacturer || '未知制造商';
    manufacturerCounts[manufacturer] = (manufacturerCounts[manufacturer] || 0) + 1;
  });

  const statusSeriesData = Object.keys(statusCounts).map(key => ({
    name: key,
    value: statusCounts[key]
  }));

  const manufacturerSeriesData = Object.keys(manufacturerCounts).map(key => ({
    name: key,
    value: manufacturerCounts[key]
  }));

  // 更新图表
  updateDeviceStatusChart(statusSeriesData);
  updateManufacturerChart(manufacturerSeriesData);
}

/**
 * 初始化并更新设备状态分布图 (饼图)
 * @param {Array} seriesData - 图表数据
 */
function updateDeviceStatusChart(seriesData) {
  const chartDom = document.getElementById('deviceStatusChart');
  if (!chartDom) return;

  if (!deviceStatusChartInstance) {
    deviceStatusChartInstance = echarts.init(chartDom);
  }

  const option = {
    title: {
      text: '设备状态分布',
      subtext: '基于当前查询结果',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '设备状态',
        type: 'pie',
        radius: '50%',
        center: ['50%', '60%'],
        // 修正：无数据时显示占位，并隐藏标签和指示线
        data: seriesData.length > 0 ? seriesData : [{ value: 1, name: '暂无数据', itemStyle: { color: '#ccc' } }],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: seriesData.length > 0, // 无数据时不显示标签
          formatter: '{b} ({d}%)'
        },
        labelLine: {
          show: seriesData.length > 0
        },
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200;
        }
      }
    ]
  };
  deviceStatusChartInstance.setOption(option);
}

/**
 * 初始化并更新制造商设备数量图 (柱状图)
 * @param {Array} seriesData - 图表数据
 */
function updateManufacturerChart(seriesData) {
  const chartDom = document.getElementById('manufacturerChart');
  if (!chartDom) return;

  if (!manufacturerChartInstance) {
    manufacturerChartInstance = echarts.init(chartDom);
  }

  // 优化：按照设备数量降序排序，并确保至少显示一个“暂无数据”
  const sortedSeriesData = [...seriesData].sort((a, b) => b.value - a.value);
  const categories = sortedSeriesData.map(item => item.name);
  const values = sortedSeriesData.map(item => item.value);

  // 处理无数据情况
  let markPointSetting = null;
  if (seriesData.length === 0) {
    // 当没有数据时，创建一个虚拟的“暂无数据”类别和值，并用markPoint显示文字
    // categories = ['暂无数据']; // 不直接修改，而是通过markPoint
    // values = [0]; // 不直接修改，而是通过markPoint
    markPointSetting = {
      symbol: 'none', // 不显示标记点形状
      label: {
        show: true,
        position: 'inside', // 调整位置到图表中心
        formatter: '暂无数据', // 显示的文本
        fontSize: 14,
        color: '#999'
      },
      data: [{ x: 'center', y: 'center' }] // 放置在图表中心
    };
  }

  const option = {
    title: {
      text: '制造商设备数量',
      subtext: '基于当前查询结果',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        interval: 0,
        rotate: categories.length > 4 ? 30 : 0
      }
    },
    yAxis: {
      type: 'value',
      minInterval: 1
    },
    series: [
      {
        name: '设备数量',
        type: 'bar',
        data: values,
        barWidth: '40%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: '#4CAF50' }, // 绿色系
                { offset: 0.5, color: '#66BB6A' },
                { offset: 1, color: '#81C784' }
              ]
          )
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        },
        markPoint: markPointSetting // 应用无数据时的markPoint
      }
    ]
  };
  manufacturerChartInstance.setOption(option);
}

// 监听窗口大小变化以调整图表尺寸
const resizeCharts = throttle(() => {
  deviceStatusChartInstance?.resize();
  manufacturerChartInstance?.resize();
}, 200);


/** 查询设备基本信息列表 */
function getList() {
  loading.value = true
  listInfo(queryParams.value).then(response => {
    infoList.value = response.rows // 修正：使用 infoList
    total.value = response.total
    loading.value = false
    // 数据加载完成后更新图表
    aggregateChartData(infoList.value); // 修正：使用 infoList.value
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deviceName: null,
    categoryId: null,
    model: null,
    specification: null,
    manufacturer: null,
    supplier: null,
    purchaseDate: null,
    location: null,
    status: null,
    currentValue: null,
    description: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    faultReportList: [] // 重置时清空子列表
  }
  faultReportList.value = [] // 确保响应式变量也重置
  proxy.resetForm("infoRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加设备基本信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset() // 先重置，再加载数据
  const _id = row.id || ids.value
  getInfo(_id).then(response => {
    form.value = response.data
    // 确保从后端返回的faultReportList是数组，如果为null或undefined则初始化为空数组
    faultReportList.value = response.data.faultReportList || []
    open.value = true
    title.value = "修改设备基本信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["infoRef"].validate(valid => {
    if (valid) {
      form.value.faultReportList = faultReportList.value
      if (form.value.id != null) {
        updateInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          // 修正：确保提交后刷新图表
          getList()
        })
      } else {
        addInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          // 修正：确保提交后刷新图表
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除设备基本信息编号为"' + _ids + '"的数据项？').then(function() {
    return delInfo(_ids)
  }).then(() => {
    // 修正：确保删除后刷新图表
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 故障报修序号 */
function rowFaultReportIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 故障报修添加按钮操作 */
function handleAddFaultReport() {
  let obj = {
    faultTitle: "",
    faultDesc: "", // 添加故障描述字段，用于展示长文本
    faultLevel: "",
    reportBy: "",
    reportTime: "",
    status: ""
  }
  faultReportList.value.push(obj)
}

/** 故障报修删除按钮操作 */
function handleDeleteFaultReport() {
  if (checkedFaultReport.value.length === 0) {
    proxy.$modal.msgError("请先选择要删除的故障报修数据")
  } else {
    // 过滤掉选中的行，并重新为剩余行设置索引
    faultReportList.value = faultReportList.value.filter(item => !checkedFaultReport.value.includes(item.index));
    // 清空选中项
    checkedFaultReport.value = [];
    // 强制刷新表格选中状态，确保UI同步
    proxy.$nextTick(() => {
      proxy.$refs.DFaultReport.clearSelection();
    });
  }
}

/** 复选框选中数据 */
function handleFaultReportSelectionChange(selection) {
  checkedFaultReport.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('device/info/export', {
    ...queryParams.value
  }, `info_${new Date().getTime()}.xlsx`)
}

// Mounted 生命周期钩子：初始化图表并添加窗口resize监听
onMounted(() => {
  // 在获取列表数据之前，先初始化空的图表，防止DOM还没渲染好就尝试获取元素
  updateDeviceStatusChart([]); // 传入空数组初始化无数据状态
  updateManufacturerChart([]); // 传入空数组初始化无数据状态

  // 添加窗口resize事件监听
  window.addEventListener('resize', resizeCharts);

  // 第一次加载列表数据
  getList();
});

// Unmounted 生命周期钩子：销毁图表实例并移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts);
  deviceStatusChartInstance?.dispose(); // 销毁 ECharts 实例，防止内存泄漏
  manufacturerChartInstance?.dispose();
});
</script>

<style scoped>
/* 可以在这里添加一些样式来微调布局，例如： */
.el-row {
  margin-bottom: 10px; /* 增加行之间的间距，保持视觉平衡 */
}
.el-form-item {
  margin-bottom: 0px; /* 在el-row中已经有间距，减少form-item自带的冗余间距 */
}

/* 统计图表区域样式 */
.chart-section {
  margin-bottom: 20px; /* 图表卡片与下方表格的间距 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.chart-container {
  height: 300px; /* 为图表设置固定高度 */
  width: 100%; /* 宽度自动填充父容器 */
}
</style>
